<template>
  <el-dialog width="500px" v-bind="$attrs" @close="handleClose" @opened="handleOpened">
    <el-form
      v-show="!ramKey"
      ref="showForm"
      :model="showForm"
      :rules="rules"
      
      @submit.prevent.native
      label-width="auto"
    >
      <el-form-item :label="$t('system.ram.password')" prop="operPassword">
        <el-input v-model="showForm.operPassword" type="password" @blur="() => showForm.operPassword = showForm.operPassword.trim()" />
      </el-form-item>
      <!-- captcha -->
      <el-form-item v-if="!OTP" prop="code" :label="$t('system.ram.captcha')">
        <div style="display: flex;gap: 16px; width: 100%;">
          <el-input v-model="showForm.code" style="flex: auto;">
          </el-input>
          <img ref="img" @click="getCaptcha" style="height: 32px; flex:none" class=" cursor-pointer" />
        </div>
      </el-form-item>
      <!-- otp -->
      <el-form-item v-if="OTP" prop="otpToken" :label="$t('user.otp.otp_code')">
        <el-input v-model="showForm.otpToken">
        </el-input>
      </el-form-item>
      <div class="el-form-item__error text-center">{{ invalidMessage }}</div>
    </el-form>
    <el-row v-show="ramKey" class="mx-6">
      <el-col :span="21">
        <el-input v-model="ramKey" :readonly="true"  />
      </el-col>
      <el-col :span="2" class=" mt-2 ml-1">
        <svg-icon
                class="cursor-pointer hover:text-blue-1"
                icon-class="outlined-copy"
                style="font-size:20px" @click="copyKey()"
                />
      </el-col>
    </el-row>
    <template #footer>

      <span class="dialog-footer">
        <el-button v-show="!ramKey"  @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button  type="primary" :loading="confirmLoading" @click="showRamKey">
          {{ $t('common.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  props: ['userId'],
  data() {
    return {
      invalidMessage: '',
      OTP: false,
      ramKey: '',
      confirmLoading: false,
      captchaImgSrc: '',
      showForm: {
        userId: null,
        operPassword: '',
        code: '',
        otpToken: ''
      },
      rules: {
        operPassword: [
          {
            required: true,
            message: this.$t('modules.login.message.validate_password_required'),
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: this.$t('modules.login.message.validate_code_required'),
            trigger: 'blur'
          }
        ],
        otpToken: [
          {
            required: true,
            message: this.$t('system.ram.validate_require'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {

    copyKey() {
      var textarea = document.createElement('textarea')
      textarea.value = this.ramKey
      // 添加input标签
      document.body.appendChild(textarea)
      // 选中input标签
      textarea.select()
      // 执行复制
      document.execCommand('copy')
      // 成功提示信息
      this.$message.success('Copy Success!')
      // 移除input标签
      document.body.removeChild(textarea)
    },
    getCaptcha() {
      const prefix = import.meta.env.VITE_APP_BASE_API;
      this.captchaImgSrc =
        prefix +
        `/online/authorization/ram/security/verify/code/ram/${this.userId}/show`
      let _this = this
      let request = new XMLHttpRequest();
      request.responseType = "blob";
      request.open("get", this.captchaImgSrc, true);
      request.setRequestHeader("WEB-TOKEN", getToken());
      request.onreadystatechange = (e) => {
        if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
          let fr = new FileReader()
          fr.readAsText(request.response)
          fr.onload = function (e) {
            let result = fr.result
            let resultObj = JSON.parse(fr.result)
            if (resultObj.code === "1096") {
              _this.OTP = true
            }
            else {
              _this.OTP = false
              _this.$nextTick(() => {
                let img = _this.$refs.img;
                img.src = resultObj.captcha
              })
            }
          }
        } else if (request.readyState == XMLHttpRequest.DONE) {

          let fr = new FileReader()
          fr.readAsText(request.response)
          fr.onload = function (e) {
            let resultObj = JSON.parse(fr.result)
            _this.invalidMessage = resultObj.message
          }
        }
      };
      request.send(null);
    },
    handleClose() {
      this.$refs['showForm'].resetFields()
      this.ramKey = ''
      this.confirmLoading = false
      this.$emit('update:model-value', false)
    },

    handleOpened() {
      this.getCaptcha()
    },
    showRamKey() {
      if (this.ramKey) {
        this.handleClose()
      } else {
        this.$refs['showForm'].validate((valid) => {
          if (valid) {
            this.confirmLoading = true
            this.showForm.userId = this.userId
            this.$store
              .dispatch('user/getRamKey', this.showForm).then((res) => {
                this.ramKey = res
              })
              .catch(this.$confirmError).finally(() => {
                this.getCaptcha()
                this.showForm.code = ''
                this.showForm.operPassword = ''
                this.confirmLoading = false
              })
          }
        })
      }
    }
  }
}
</script>

<style>
</style>
